import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtInput} from "taro-ui";
import {View} from "@tarojs/components";
import {DOUYIN_BUSINFORM, TARO_ENV} from '../../constants/api';
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {vcmonitor, GetRequest} from "../../utils/tools";
import {h5Wx} from '../../utils/h5.service';
import './businessList.scss'
import {newHttp} from "../../utils/request";

type PageState = {
  name: any
  tiktok_visitor_id: any
  itemId: any
}

export default class BusinessInfo extends Component {
  state: PageState = {
    name: '',
    tiktok_visitor_id: '',
    itemId: ''
  }

  async UNSAFE_componentWillMount() {
    await vcmonitor(this)
    if (TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    this.getData()
  }

  async getData() {
    const itemId = Taro.getCurrentInstance().router.params.itemId
    if (itemId) {
      const tableData = await newHttp.get(DOUYIN_BUSINFORM, {id: itemId, page: 1, length: 9999999})
      if (tableData && tableData.data.length > 0) {
        this.setState({
          name: tableData.data[0].name,
          tiktok_visitor_id: tableData.data[0].tiktok_visitor_id,
          itemId
        })
      }
    }
  }

  handleChange(field, val) {
    this.setState({[field]: val})
  }

  async save(flag = 0) {
    await Taro.showLoading({title: '加载中...', mask: true})
    const {name, tiktok_visitor_id, itemId} = this.state
    const id = Taro.getCurrentInstance().router.params.itemId
    let params
    if (Taro.getCurrentInstance().router.params.itemId) {
      params = {name, tiktok_visitor_id,id}
    } else {
      params = {name, tiktok_visitor_id}
    }
    const data = await newHttp.catchPost('/msvc-shop/v1/douyin/addbus', params)
    if (data) {
      await Taro.navigateBack({delta: 1})
    } else {
      Taro.showToast({
        title: data.message,
        icon: 'none',
        mask: true
      });
    }
  }

  render() {
    const {name, tiktok_visitor_id} = this.state
    return (
      <View className='business-info'>
        <GzhAuth />
        <AtInput
          name='name'
          title='商家名称'
          type='text'
          placeholder='请输入商家名称'
          value={name}
          onChange={this.handleChange.bind(this, 'name')}
        />
        <AtInput
          border={false}
          name='lkId'
          title='抖音来客ID'
          type='text'
          placeholder='请输入抖音来客ID'
          value={tiktok_visitor_id}
          onChange={this.handleChange.bind(this, 'tiktok_visitor_id')}
        />
        <View className='foot-btn'>
          <View className={`${TARO_ENV === 'h5' ? "btn h5-small active" : "btn active"}`}
                onClick={() => this.save(1)}
          >保存并提交</View>
        </View>
      </View>
    )
  }
}
